using Microsoft.Extensions.Options;

namespace ThingsGateway.Application.Core;


/// <summary>
/// 设备变量API服务
/// </summary>
[ApiDescriptionSettings(ApplicationConst.RunTimeGroupName, Order = 301)]
public class DeviceVariableRunTimeService : IDynamicApiController, ITransient
{
    private readonly DeviceCollectService _deviceCollectService;
    private readonly SqlSugarRepository<DeviceVariable> _deviceVariableRep;
    private readonly SqlSugarRepository<DeviceProperty> _devicePropertyRep;
    private readonly SqlSugarRepository<Device> _deviceRep;
    private readonly UploadOptions _uploadOptions;
    private readonly SysCacheService _sysCacheService;
    /// <summary>
    /// 网关数据都做了数据权限，所以RunTime数据也需要判断数据权限，这里直接使用数据库返回的标识再筛选
    /// </summary>
    public DeviceVariableRunTimeService(
        SqlSugarRepository<DeviceVariable> deviceVariableRep,
        SqlSugarRepository<Device> deviceRep, IOptions<UploadOptions> uploadOptions,
        SqlSugarRepository<DeviceProperty> devicePropertyRep,
        RootServices rootServices,
        SysCacheService sysCacheService)
    {
        _uploadOptions = uploadOptions.Value;
        _deviceVariableRep = deviceVariableRep;
        _deviceRep = deviceRep;
        _sysCacheService = sysCacheService; _devicePropertyRep = devicePropertyRep;
        _deviceCollectService = rootServices.DeviceCollectService;
    }

    /// <summary>
    /// 获取设备变量分页列表
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [HttpGet("/collectstatus/deviceVariable/page")]
    public async Task<SqlSugarPagedList<DeviceVariable>> GetDeviceVariablePage([FromQuery] PageDeviceVariableInput input)
    {
        var runTimeData = _deviceCollectService.DeviceCollectCores.SelectMany(it => it.DeviceVariablesCopy)
            ?.WhereIF(!string.IsNullOrWhiteSpace(input.Name?.Trim()), u => u.Name.Contains(input.Name))
            ?.WhereIF(!string.IsNullOrWhiteSpace(input.DeviceName?.Trim()),
            u => _deviceCollectService.DevIdNames.FirstOrDefault(it => it.Id == u.DeviceId).Name.Contains(input.DeviceName)).ToList();
        var data = await runTimeData?.ToPagedListAsync(input.Page, input.PageSize);
        return data;

    }


    /// <summary>
    /// 写入值
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [HttpPost("/collectstatus/deviceVariable/write")]
    public async Task<bool> WriteDeviceVariableValue(WriteDeviceVariableInput input)
    {
        var data = await _deviceCollectService.InvokeDeviceMed(input.DeviceName, "WRITE", new Dictionary<string, object>()
        {
            {  input.Name,input.WriteValue }
        }
        );
        if (data.IsSuccess) return true;
        else throw new Exception(data.Message);

    }


}